package com.imooc.cpp.service;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.cpp.dto.ChapterWrapper;
import com.imooc.cpp.entity.Chapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class ChapterService {

    @Resource
    private DefaultMQProducer producer;

    public void publish(Chapter chapter){
        log.debug("Chapter已处理完毕，准备推送至Broker");

        ObjectMapper mapper = new ObjectMapper();
        // 属性为null  不进行序列化
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        try {
            ChapterWrapper chapterWrapper = new ChapterWrapper(chapter);

            String portalData = mapper.writeValueAsString(chapterWrapper.getChapter("PORTAL"));
            Message portalMessage = new Message("PORTAL", "", portalData.getBytes());
            SendResult portalResult= producer.send(portalMessage);
            log.debug("PORTAL 消息主题已发送，MsgID"+portalResult.getMsgId()+ " 发送状态："+portalResult.getSendStatus());


            String advData = mapper.writeValueAsString(chapterWrapper.getChapter("ADV"));
            Message advMessage = new Message("ADV", "", advData.getBytes());
            SendResult advResult= producer.send(advMessage);
            log.debug("ADV 消息主题已发送，MsgID"+advResult.getMsgId()+ " 发送状态："+ advResult.getSendStatus());



        } catch (Exception e) {
            log.error("MQ消息发送失败！");
            throw new RuntimeException(e);
        }
    }
}
